import streamlit as st
import os
from pathlib import Path

# 导入自定义模块
from src.ui.main_page import render_main_page
from src.ui.config_page import render_config_page, initialize_config_from_file
from src.ui.preview_page import render_preview_page
from src.ui.download_page import render_download_page
from src.ui.help_page import render_help_page
from src.utils.session_state import init_session_state

# 页面配置
st.set_page_config(
    page_title="数据预处理工具",
    page_icon="📄",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# 自定义CSS样式
st.markdown("""
<style>
    .main-header {
        font-size: 2.5rem;
        color: #2563eb;
        text-align: center;
        margin-bottom: 2rem;
        font-weight: bold;
    }
    .nav-header {
        background: linear-gradient(90deg, #2563eb, #3b82f6);
        padding: 1rem 2rem;
        border-radius: 10px;
        margin-bottom: 2rem;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    .nav-title {
        color: white;
        font-size: 1.8rem;
        font-weight: bold;
        margin: 0;
        text-align: center;
    }
    .status-container {
        background: #f8fafc;
        padding: 1rem;
        border-radius: 8px;
        margin-bottom: 1rem;
        border-left: 4px solid #3b82f6;
    }
    .status-success {
        color: #10b981;
        font-weight: bold;
    }
    .status-warning {
        color: #f59e0b;
        font-weight: bold;
    }
    .status-error {
        color: #ef4444;
        font-weight: bold;
    }
    .stTabs [data-baseweb="tab-list"] {
        gap: 8px;
        background-color: #f1f5f9;
        padding: 8px;
        border-radius: 10px;
    }
    .stTabs [data-baseweb="tab"] {
        height: 50px;
        padding: 0px 24px;
        background-color: white;
        border-radius: 8px;
        color: #64748b;
        font-weight: 500;
        border: 1px solid #e2e8f0;
        transition: all 0.2s;
    }
    .stTabs [aria-selected="true"] {
        background-color: #3b82f6 !important;
        color: white !important;
        border-color: #3b82f6 !important;
        box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
    }
</style>
""", unsafe_allow_html=True)

def main():
    """主应用函数"""
    # 初始化会话状态
    init_session_state()
    
    # 初始化配置（从文件加载）
    initialize_config_from_file()
    
    # 顶部导航栏
    st.markdown('<div class="nav-header"><h1 class="nav-title">📄 数据预处理工具</h1></div>', unsafe_allow_html=True)
    
    # 状态显示区域
    status_col1, status_col2, status_col3 = st.columns([1, 1, 2])
    
    with status_col1:
        if st.session_state.get('uploaded_files'):
            st.markdown(f'<div class="status-container"><span class="status-success">📁 已上传 {len(st.session_state.uploaded_files)} 个文件</span></div>', unsafe_allow_html=True)
        else:
            st.markdown('<div class="status-container">📁 暂无上传文件</div>', unsafe_allow_html=True)
    
    with status_col2:
        if st.session_state.get('processing_status'):
            status = st.session_state.processing_status
            if status == 'completed':
                st.markdown('<div class="status-container"><span class="status-success">✅ 处理完成</span></div>', unsafe_allow_html=True)
            elif status == 'processing':
                st.markdown('<div class="status-container"><span class="status-warning">⏳ 正在处理...</span></div>', unsafe_allow_html=True)
            elif status == 'error':
                st.markdown('<div class="status-container"><span class="status-error">❌ 处理出错</span></div>', unsafe_allow_html=True)
        else:
            st.markdown('<div class="status-container">⏸️ 等待处理</div>', unsafe_allow_html=True)
    
    with status_col3:
        if st.session_state.get('processed_documents'):
            total_chunks = sum(len(doc.get('chunks', [])) for doc in st.session_state.processed_documents)
            st.markdown(f'<div class="status-container">✂️ 已生成 {total_chunks} 个切片</div>', unsafe_allow_html=True)
    
    # 检查query_params中的页面参数
    query_page = st.query_params.get("page", "主页面")
    page_list = ["🏠 主页面", "⚙️ 处理配置", "👀 结果预览", "📥 下载管理", "❓ 帮助文档"]
    page_mapping = {
        "🏠 主页面": "主页面",
        "⚙️ 处理配置": "处理配置", 
        "👀 结果预览": "结果预览",
        "📥 下载管理": "下载管理",
        "❓ 帮助文档": "帮助文档"
    }
    
    # 找到当前页面对应的tab索引
    current_page = "主页面"
    for tab_name, page_name in page_mapping.items():
        if page_name == query_page:
            current_page = page_name
            break
    
    # 创建标签页导航
    tab1, tab2, tab3, tab4, tab5 = st.tabs(page_list)
    
    # 直接显示各页面内容
    with tab1:
        render_main_page()
    
    with tab2:
        render_config_page()
    
    with tab3:
        render_preview_page()
    
    with tab4:
        render_download_page()
    
    with tab5:
        render_help_page()

if __name__ == "__main__":
    main()